import config from "./config";

export default {
  data() {
    return {
      mqttUrl: "wss://srs.hiwords.net/mqtt",
      publish: {
        topic: "topic/sgb",
        qos: 1,
      },
      // 订阅主题
      subscription: {
        topic: "topic/sgb",
        qos: 1,
      },
      mqttOptions: {
        // Clean session
        clean: true,
        connectTimeout: 4000,
        // 认证信息
        clientId: `sgb_${+new Date()}`,
        username: `sgb_${+new Date()}_name`,
        password: "emqx_test",
      },
      client: null,
    };
  },
  mounted() {},
  destroyed() {
    this.destroyConnection();
  },
  methods: {
    createConnection({ onConnect, onMessage }) {
      try {
        this.client = this.mqtt.connect(this.mqttUrl, this.mqttOptions);
        if (this.client.on) {
          this.client.on("connect", () => {
            this.connecting = false;
            onConnect();
            console.log("Connection succeeded!");
          });
          // this.client.on('reconnect', this.handleOnReConnect)
          this.client.on("error", (error) => {
            console.log("Connection failed", error);
          });
          this.client.on("message", (topic, message) => {
            // console.log(`Received message ${message} from topic ${topic}`)
            console.log(`from topic ${topic}`, JSON.parse(message));
            try {
              onMessage && onMessage(JSON.parse(message));
            } catch (err) {
              console.log("收到错误-->", err);
              onMessage && onMessage(null);
            }
          });
        }
      } catch (error) {
        this.connecting = false;
        console.log("mqtt.connect error", error);
      }
    },
    // 订阅主题
    doSubscribe(id) {
      const { topic, qos } = this.subscription;
      this.client.subscribe(`${topic}/${id}`, { qos }, (error, res) => {
        if (error) {
          console.log("Subscribe to topics error", error);
          return;
        }
        this.subscribeSuccess = true;
        console.log("Subscribe to topics res", res);
      });
    },
    // 断开连接
    destroyConnection() {
      if (this.client.connected) {
        try {
          this.client.end(false, () => {
            console.log("Successfully disconnected!");
          });
        } catch (error) {
          console.log("Disconnect failed", error.toString());
        }
      }
    },
    // 发布消息
    doPublish({ id, payload }) {
      return new Promise((resolve, reject) => {
        const { topic, qos } = this.publish;
        const json = JSON.stringify(payload);
        this.client.publish(`${topic}/${id}`, json, { qos, retain: true }, (error) => {
          if (error) {
            return reject();
          }
          return resolve();
        });
      });
    },
    update(id, payload) {
      const keys = Object.keys(config);
      const tmp = {};
      for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        tmp[key] = this[key];
      }
      if (payload.field !== "currentLyric") {
        tmp.currentLyric = this.currentLyric;
      }
      tmp[payload.field] = payload.value;
      tmp.username = this.mqttOptions.username;
      console.log("tmp", tmp);
      return this.doPublish({ id, payload: tmp });
    },
    get() {},
  },
};
